﻿using System;
using System.IO;
using System.Text.RegularExpressions;

public class ReverseEgn
{
    private const string INPUT_FILE_NAME = @"..\..\..\ReverseEgn\persons.txt";

    public static void Main()
    {
        StreamReader input = new StreamReader(INPUT_FILE_NAME);
        string pattern = @"[0-9]{10}";
        using (input)
        {
            string tempFileName = Path.GetTempFileName();
            StreamWriter output = new StreamWriter(tempFileName);
            using (output)
            {
                while (!input.EndOfStream)
                {
                    string text = input.ReadLine();
                    int startIndex = 0;
                    Match m = Regex.Match(text, pattern, RegexOptions.None);
                    while (m.Success)
                    {
                        output.Write(text.Substring(startIndex, m.Index-startIndex));
                        startIndex = m.Index;
                        if (VerifyMatch(m.Value))
                        {
                            for (int i = 0; i < m.Value.Length; i++)
                            {
                                output.Write(m.Value[m.Value.Length - i - 1]);
                            }
                        }
                        else
                        {
                            output.Write(m.Value);
                        }
                        startIndex += m.Length;
                        m = m.NextMatch();
                    }
                    output.WriteLine(text.Substring(startIndex));
                }
            }
            input.Close();
            File.Delete(INPUT_FILE_NAME);
            Directory.Move(tempFileName, INPUT_FILE_NAME);
            File.Delete(tempFileName);
        }
    }

    private static bool VerifyMatch(string match)
    {
        int year = int.Parse(match.Substring(0, 2));
        int month = int.Parse(match.Substring(2, 2));
        int day = int.Parse(match.Substring(4, 2));
        try
        {
            DateTime birthDate = new DateTime(year, month, day);
        }
        catch (ArgumentOutOfRangeException ex)
        {
            //EGN was with invalid date
            return false;
        }
        return true;
    }


}
